var Q = require('q');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var DB_CONN_STR = 'mongodb://localhost:27017/zfjly';
var DB;
function Manager () {}

Manager.prototype.connect = function () {
    MongoClient.connect(DB_CONN_STR, function(err,db) {
        if(err) return console.log(err.message)
        console.log("连接成功！");
        DB = db
    })
}
Manager.prototype.insert = function (collectionName, data, callback) {
    //连接到表
    var collection = DB.collection(collectionName);
    //插入数据
    collection.insert(data, function(err, result) {
        if(err){
            console.log('Error:'+ err);
            callback({success:false,result:err,message:'insert'+collectionName+'失败'});
            return;
        }
        callback({success:true,result:result,message:''});
    });
};
Manager.prototype.update = function (collectionName, where, update, callback) {
    //连接到表  
    var collection = DB.collection(collectionName);
    // var whereStr = {"name":'zsc'};
    // var updateStr = {$set: { "password" : "8888" }};
    if(where._id){
        where._id=new ObjectID(where._id);
    }
    var updateData={$set: update};
    collection.update(where,updateData, function(err, result) {
        if(err){
            console.log('Error:'+ err);
            callback({success:false,result:err,message:'update'+collectionName+'失败'});
            return;
        }
        callback({success:true,result:result,message:''});
    });
};
//要更新数组的更新表方法
Manager.prototype.updateArr = function (collectionName, where, update, callback) {
    //连接到表
    var collection = DB.collection(collectionName);
    // var whereStr = {"name":'zsc'};
    // var updateStr = {$set: { "password" : "8888" }};
    if(where._id){
        where._id=new ObjectID(where._id);
    }
    collection.update(where,update, function(err, result) {
        if(err){
            console.log('Error:'+ err);
            callback({success:false,result:err,message:'update'+collectionName+'失败'});
            return;
        }
        callback({success:true,result:result,message:''});
    });
};
Manager.prototype.find = function (collectionName, where, sort, callback) {
    //连接到表
    var collection = DB.collection(collectionName);
    //默认排序
    var sort = sort || {_id:-1};
    //查询数据
    //var whereStr = {"name":'菜鸟教程'};
    console.log("where::",where)
    var query = {
        "wjlx": new RegExp(where.wjlx)
    }
    if(where.pssj){
        query.pssj = {
            $gte: new Date(where.pssj)
        }
    }
    console.log(query)
    collection.find(query,{sort:sort}).toArray(function(err, result) {
        if(err){
            console.log('Error:'+ err);
            callback({success:false,result:err,message:'find'+collectionName+'失败'});
            return;
        }
        callback({success:true,result:result,message:''});
    });
};

//同步查找数据库
Manager.prototype.findAsync = function (collectionName, where, sort, callback) {
    var deferred = Q.defer();
    //连接到表
    var collection = DB.collection(collectionName);
    //默认排序
    var sort = sort || {_id:-1};
    //查询数据
    collection.find(where,{sort:sort}).toArray(function(err,result){
        if(!err){
            deferred.resolve(result);
        }else {
            deferred.reject(err);
        }
    });
    return deferred.promise;
};



//去重查找数据库
Manager.prototype.findAsyncDistinct = function(collectionName, distinct, where, callback) {
    var deferred = Q.defer();
    //连接到表
    var collection = DB.collection(collectionName);
    //查询数据
    collection.distinct(distinct, where, function(err, result) {
        if (!err) {
            deferred.resolve(result);
        } else {
            deferred.reject(err);
        }
    });
    return deferred.promise;
};




Manager.prototype.findByPage = function (collectionName, where, page, pageSize, sort, callback) {
    //连接到表  
    var collection = DB.collection(collectionName);
    //默认排序
    var sort = sort || {_id:-1};
    //默认一页的个数
    var pageSize = pageSize || 5;
    //查询数据
    //var whereStr = {"name":'菜鸟教程'};
    var total;
    collection.find(where,{sort:sort}).count(function(err, result){
        if(err){
            console.log('Error:'+ err);
            return;
        }
        total=result;
        // console.log(total);
        collection.find(where,{sort:sort,skip:(page-1)*pageSize,limit:pageSize}).toArray(function(err, result) {
            if(err){
                console.log('Error:'+ err);
                callback({success:false,result:err,message:'find'+collectionName+'失败'});
                return;
            }
            callback({success:true,result:{data:result,total:total},message:''});
        });
    });
};


Manager.prototype.findOne = function (collectionName, where, callback) {
    //连接到表
    var collection = DB.collection(collectionName);
    if(where._id){
        where._id=new ObjectID(where._id);
    }
    //查询数据
    collection.findOne(where,function(err, result) {
        if(err){
            console.log('Error:'+ err);
            callback({success:false,result:err,message:'find'+collectionName+'失败'});
            return;
        }
        callback({success:true,result:result,message:''});
    });
};
//同步查找数据库
Manager.prototype.findOneAsync = function (collectionName, where, callback) {
    var deferred = Q.defer();
    //连接到表
    var collection = DB.collection(collectionName);
    if(where._id){
        where._id=new ObjectID(where._id);
    }
    //查询数据
    collection.findOne(where,function(err, result) {
        if(!err){
            deferred.resolve(result);
        }else {
            deferred.reject(err);
        }
    });
    return deferred.promise;
};

Manager.prototype.delete = function (collectionName, where, callback) {
    //连接到表
    var collection = DB.collection(collectionName);
    //删除数据
    //var whereStr = {"name":'菜鸟工具'};
    if(where._id){
        where._id=new ObjectID(where._id);
    }
    // console.log(where);
    collection.remove(where, function(err, result) {
        if(err){
            console.log('Error:'+ err);
            callback({success:false,result:err,message:'delete'+collectionName+'失败'});
            return;
        }
        callback({success:true,result:result,message:''});
    });
};